﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using UnityEngine;
using Warensoft.Unity.Communication.Client;
using Warensoft.Unity.Communication.Client.DataClient;

public class CommunicationManager
{
    public static event EventHandler SceneUpdate;
    private static Dictionary<string, DataContext> dataContexts = new Dictionary<string, DataContext>();
    private static CommunicationManager currentInstance;

    public static CommunicationManager CreateInstance()
    {
        if (currentInstance == null)
        {
            currentInstance = new CommunicationManager();
        }
        return currentInstance;
    }

    static CommunicationManager()
    {

    }
    public void Update()
    {
        
        if (SceneUpdate != null)
        {
            
            SceneUpdate(this, new EventArgs());
        }
    }
    public SocketClient ConnectTcp(IPAddress ip, int port)
    {
        SocketClient client = new SocketClient();

        client.Connect(ip, port);
        return client;
    }
    public HttpClient GetHttpClient()
    {
        return HttpClient.CreateInstance();
    }
    public DataContext CreateDataContext(string serviceUrl)
    {
        if (!dataContexts.ContainsKey(serviceUrl))
        {
            DataContext context = new DataContext(serviceUrl);
            dataContexts.Add(serviceUrl, context);
        }
        return dataContexts[serviceUrl];

    }
}



public class UnityCommunicationManager : MonoBehaviour
{
    public static event EventHandler SceneUpdate;
    private static Dictionary<string, DataContext> dataContexts = new Dictionary<string, DataContext>();
    private static UnityCommunicationManager currentInstance;
    private CommunicationManager cm;
    public static UnityCommunicationManager CreateInstance()
    {
        if (currentInstance == null)
        {
            currentInstance = Camera.main.gameObject.AddComponent<UnityCommunicationManager>();
            currentInstance.cm = new CommunicationManager();
        }
        return currentInstance;
    }

    static UnityCommunicationManager()
    {

    }
    public void Update()
    {
        try
        {
            this.cm.Update();
        }
        catch (Exception ex)
        {

            MonoBehaviour.print("error:"+ex.Message+"\n"+ex.StackTrace);
        }
        
        
    }
    public SocketClient ConnectTcp(IPAddress ip, int port)
    {
        return this.cm.ConnectTcp(ip, port);
    }
    public UnityHttpClient GetHttpClient()
    {
        return UnityHttpClient.CreateInstance();
    }
    public DataContext CreateDataContext(string serviceUrl)
    {
        return this.cm.CreateDataContext(serviceUrl);

    }
}

